<template>
	<view class="content">
		<!-- API Key输入弹窗 -->
		<view v-if="showKeyInput" class="key-input-overlay">
			<view class="key-input-container">
				<text class="key-input-title">请输入您的 API Key</text>
				<input 
					type="text" 
					v-model="tempApiKey"
					placeholder="请输入以sk-开头的API Key" 
					class="key-input-field"
					@confirm="saveApiKey"
					:maxlength="-1"
				/>
				<button class="key-submit-btn" @click="saveApiKey">确认</button>
			</view>
		</view>
		
		<!-- 顶部区域 -->
		<view class="header-box">
			<image src="../../static/Chatgpt.png" class="header-img"></image>
			<text>HELLO! 欢迎您</text>
		</view>
		<view v-if="responseText == ''" class="content-blank"></view>
		<!-- 中间内容区域 -->
		<view class="content-box" v-else>
			<view class="content-body">
				<scroll-view scroll-y="true" class="scroll-view" :scroll-top="scrollTop">
					<view class="chat-container">
						<!-- 消息列表 -->
						<template v-for="(message, index) in messageList" :key="index">
							<!-- AI回复 -->
							<view v-if="message.type === 'ai'" class="chat-item chat-left">
								<image src="../../static/Chatgpt.png" class="chat-avatar"></image>
								<view class="chat-bubble chat-bubble-left">
									<view class="typewriter-text">
										{{ message.displayText }}
									</view>
									<view v-if="message.isComplete" class="copy-button" @click="copyText(message.content)">
										<image src="../../static/copy.png" class="copy-icon"></image>
									</view>
								</view>
							</view>
							<!-- 用户消息 -->
							<view v-else class="chat-item chat-right">
								<view class="chat-bubble chat-bubble-right">
									<view class="message-text">{{ message.content }}</view>
								</view>
								<image src="../../static/user.png" class="chat-avatar"></image>
							</view>
						</template>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="bottom-box">
			<!-- 左侧消息 -->
			<view class="bottom-left-input">
				<textarea 
					type="text" 
					placeholder="请输入发送的信息" 
					v-model="inputContent"
					@keypress.enter.prevent="handleSend"
					class="input-field"
					auto-height
					:maxlength="-1"
					:show-confirm-bar="false"
				/>
			</view>
			<!-- 右侧发送按钮 -->
			<view class="bottom-right-btn" @click="handleSend">
				<image src="../../static/send.png" class="bottom-img-send"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import openAI from 'openai';
	export default {
		data() {
			return {
				inputContent: '',
				responseText: '',
				displayText: '',
				typewriterInterval: null,
				messageList: [],
				scrollTop: 0,
				isTyping: false,
				contextMessages: [],
				maxContextLength: 10,
				showKeyInput: false,
				tempApiKey: '',
				key: ''
			}
		},
		onLoad() {
			// 从本地存储获取API Key
			try {
				const storedKey = uni.getStorageSync('openai_api_key');
				if (storedKey) {
					this.key = 'Bearer ' + storedKey;
					// 初始化系统消息并发送欢迎消息
					this.initChat(true);
				} else {
					this.showKeyInput = true;
				}
			} catch (e) {
				console.error('获取存储的API Key失败:', e);
				this.showKeyInput = true;
			}
		},
		methods: {
			initChat(sendWelcome = false) {
				this.contextMessages = [{
					role: 'system',
					content: '你是一个有帮助的AI助手，请根据上下文提供准确和有帮助的回答。'
				}];
				
				if (sendWelcome) {
					this.send('你好');
				}
			},
			saveApiKey() {
				if (!this.tempApiKey.trim()) {
					uni.showToast({
						title: '请输入API Key',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.setStorageSync('openai_api_key', this.tempApiKey);
					this.key = this.tempApiKey.startsWith('Bearer ') ? this.tempApiKey : 'Bearer ' + this.tempApiKey;
					this.showKeyInput = false;
					// 初始化系统消息并发送欢迎消息
					this.initChat(true);
				} catch (e) {
					console.error('保存API Key失败:', e);
					uni.showToast({
						title: '保存API Key失败',
						icon: 'none'
					});
				}
			},
			handleSend() {
				if (!this.inputContent.trim()) return;
				
				// 添加用户消息到界面显示
				this.messageList.push({
					type: 'user',
					content: this.inputContent
				});
				
				// 添加用户消息到上下文
				this.contextMessages.push({
					role: 'user',
					content: this.inputContent
				});
				
				// 发送消息
				this.send(this.inputContent);
				
				// 清空输入框
				this.inputContent = '';
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom();
				});
			},
			scrollToBottom() {
				// 仅在用户发送消息时自动滚动到底部
				if (!this.isTyping) {
					this.$nextTick(() => {
						this.scrollTop = Math.random();
					});
				}
			},
			typewriterEffect(messageIndex) {
				const message = this.messageList[messageIndex];
				let index = 0;
				message.displayText = '';
				message.isComplete = false;
				this.isTyping = true;
				
				clearInterval(this.typewriterInterval);
				
				this.typewriterInterval = setInterval(() => {
					if (index < message.content.length) {
						message.displayText += message.content[index];
						index++;
					} else {
						clearInterval(this.typewriterInterval);
						message.isComplete = true;
						this.isTyping = false;
					}
				}, 20);
			},
			async send(content) {
				// 保持上下文长度在限制范围内
				if (this.contextMessages.length > this.maxContextLength) {
					// 保留系统消息和最近的消息
					this.contextMessages = [
						this.contextMessages[0],
						...this.contextMessages.slice(-(this.maxContextLength - 1))
					];
				}

				uni.request({
					url: 'https://api.openai.com/v1/chat/completions',
					method: 'POST',
					header: {
					  'Content-Type': 'application/json',
					  'Authorization': this.key
					},
					data: {
					  model: "gpt-4o-mini",
					  messages: this.contextMessages,
					  temperature: 0.7
					},
					success: (res) => {
					  if (res.statusCode === 200) {
						const aiResponse = res.data.choices[0].message.content.trim();
						this.responseText = aiResponse;
						
						// 添加AI回复到上下文
						this.contextMessages.push({
							role: 'assistant',
							content: aiResponse
						});
						
						// 添加AI回复到消息列表
						this.messageList.push({
							type: 'ai',
							content: aiResponse,
							displayText: '',
							isComplete: false
						});
						
						// 开始打字机效果
						this.typewriterEffect(this.messageList.length - 1);
					  } else {
						console.error('请求失败', res);
						// 添加错误提示到消息列表
						this.messageList.push({
							type: 'ai',
							content: '抱歉，API Key无效或已过期，请检查您的API Key是否正确。',
							displayText: '抱歉，API Key无效或已过期，请检查您的API Key是否正确。',
							isComplete: true
						});
						// 显示输入框重新输入
						this.showKeyInput = true;
					  }
					},
					fail: (err) => {
					  console.error('请求失败', err);
					  // 添加错误提示到消息列表
					  this.messageList.push({
						type: 'ai',
						content: 'API请求失败，请检查您的API Key是否正确或网络连接是否正常。',
						displayText: 'API请求失败，请检查您的API Key是否正确或网络连接是否正常。',
						isComplete: true
					  });
					  // 显示输入框重新输入
					  this.showKeyInput = true;
					}
				});
			},
			copyText(text) {
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({
							title: '复制成功',
							icon: 'none',
							duration: 1500
						});
					}
				});
			}
		}
	}
</script>

<style scoped>
	html, body {
		margin: 0;
		padding: 0;
		height: 100vh;
		width: 100vw;
		overflow: hidden;
	}
	
	.content {
		box-sizing: border-box;
		background-color: #000000;
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100vh;
		width: 100%;
		padding: 16rpx;
		gap: 16rpx;
		overflow: hidden;
		position: relative;
	}

	.header-box {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		max-width: 1200rpx;
		height: 70rpx;
		border-radius: 20rpx;
		font-size: clamp(24rpx, 4vw, 32rpx);
		font-weight: bolder;
		color: #ffffff;
		flex-shrink: 0;
	}
	
	.header-img {
		width: clamp(40rpx, 6vw, 60rpx);
		height: clamp(40rpx, 6vw, 60rpx);
		margin: 10rpx;
	}
	
	.content-box {
		flex: 1;
		width: 100%;
		max-width: 1200rpx;
		border: 1px solid #ffffff;
		border-radius: 20rpx;
		background-color: #ffffff;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		margin-bottom: 16rpx;
		max-height: calc(80vh - 100rpx);
	}
	
	.content-blank {
		flex: 1;
		width: 100%;
		max-width: 1200rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		opacity: 0.95;
		margin-bottom: 16rpx;
		overflow: hidden;
		max-height: calc(80vh - 100rpx);
	}
	
	.content-body {
		flex: 1;
		display: flex;
		width: 100%;
		border-radius: 20rpx;
		background-color: #ffffff;
		color: #333;
		overflow: hidden;
	}

	.bottom-box {
		position: fixed;
		bottom: 16rpx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		width: calc(100% - 32rpx);
		max-width: 1200rpx;
		background-color: #000000;
		border-radius: 50rpx;
		border: 1px solid #ffffff;
		padding: 6rpx;
		gap: 12rpx;
		flex-shrink: 0;
		z-index: 100;
		align-items: center;
	}

	.bottom-left-input {
		flex: 1;
		background-color: #ffffff;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		overflow: hidden;
		padding: 6rpx 0;
	}
	
	.bottom-right-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		min-width: 60rpx;
		width: 60rpx;
		height: 60rpx;
		background-color: #ffffff;
		border-radius: 50%;
		cursor: pointer;
		transition: all 0.2s ease;
		flex-shrink: 0;
	}
	
	.bottom-right-btn:hover {
		background-color: #f0f0f0;
		transform: scale(0.95);
		box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
	}
	
	.bottom-right-btn:active {
		background-color: #e0e0e0;
		transform: scale(0.9);
	}
	
	.bottom-img-send {
		width: 60%;
		height: 60%;
		object-fit: contain;
	}
	
	.scroll-view {
		flex: 1;
		width: 100%;
		height: 100%;
		overflow-y: auto;
	}

	.chat-container {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		padding: 16rpx;
	}

	.chat-item {
		display: flex;
		align-items: flex-start;
		gap: 12rpx;
		margin-bottom: 20rpx;
		width: 100%;
	}

	.chat-right {
		flex-direction: row;
		justify-content: flex-end;
	}

	.chat-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.chat-bubble {
		max-width: 70%;
		padding: 16rpx 24rpx;
		border-radius: 20rpx;
		position: relative;
	}

	.chat-bubble-left {
		background-color: #f0f0f0;
		color: #333;
		border-top-left-radius: 4rpx;
		padding-right: 60rpx; /* 为复制按钮留出空间 */
	}

	.chat-bubble-right {
		background-color: #007AFF;
		color: #ffffff;
		border-top-right-radius: 4rpx;
	}

	.message-text {
		font-size: clamp(24rpx, 3vw, 32rpx);
		line-height: 1.4;
		word-break: break-word;
	}

	.typewriter-text {
		white-space: pre-wrap;
		word-wrap: break-word;
		font-size: clamp(24rpx, 3vw, 32rpx);
		line-height: 1.4;
	}

	.input-field {
		width: 100%;
		padding: 10rpx 30rpx;
		border: none;
		outline: none;
		font-size: clamp(24rpx, 3vw, 32rpx);
		border-radius: 50rpx;
		box-sizing: border-box;
		line-height: 1.4;
		min-height: 48rpx;
		max-height: 200rpx;
	}

	.copy-button {
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		width: 40rpx;
		height: 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(255, 255, 255, 0.8);
		border-radius: 50%;
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.copy-button:hover {
		background-color: rgba(255, 255, 255, 1);
		transform: scale(1.1);
	}

	.copy-button:active {
		transform: scale(0.9);
	}

	.copy-icon {
		width: 24rpx;
		height: 24rpx;
		opacity: 0.6;
	}

	@media screen and (max-width: 668rpx) {
		.content {
			padding: 12rpx;
			gap: 12rpx;
		}
		
		.header-box {
			height: 60rpx;
		}
		
		.content-box,
		.content-blank {
			max-height: calc(80vh - 90rpx);
		}
		
		.bottom-box {
			bottom: 12rpx;
			width: calc(100% - 24rpx);
			padding: 4rpx;
			gap: 8rpx;
		}
		
		.bottom-right-btn {
			width: 50rpx;
			height: 50rpx;
			min-width: 50rpx;
		}
		
		.input-field {
			min-height: 40rpx;
			padding: 8rpx 24rpx;
			text-align: left;
			margin-top: 5%;
		}

		.chat-avatar {
			width: 60rpx;
			height: 60rpx;
		}

		.chat-bubble {
			padding: 12rpx 16rpx;
			max-width: 65%;
		}

		.chat-container {
			gap: 16rpx;
			padding: 12rpx;
		}

		.copy-button {
			width: 36rpx;
			height: 36rpx;
		}

		.copy-icon {
			width: 20rpx;
			height: 20rpx;
		}
	}

	.key-input-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}
	
	.key-input-container {
		background-color: #ffffff;
		padding: 40rpx;
		border-radius: 20rpx;
		width: 80%;
		max-width: 600rpx;
		display: flex;
		flex-direction: column;
		gap: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	}
	
	.key-input-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
	}
	
	.key-input-field {
		height: 80rpx;
		border: 2rpx solid #ddd;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		width: 100%;
		box-sizing: border-box;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.key-submit-btn {
		height: 80rpx;
		background-color: #007AFF;
		color: #ffffff;
		border: none;
		border-radius: 10rpx;
		font-size: 28rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		transition: all 0.2s ease;
	}
	
	.key-submit-btn:hover {
		background-color: #0056b3;
	}
	
	.key-submit-btn:active {
		transform: scale(0.98);
	}
	
	@media screen and (max-width: 668rpx) {
		.key-input-container {
			width: 90%;
			padding: 30rpx;
		}
		
		.key-input-title {
			font-size: 28rpx;
		}
		
		.key-input-field,
		.key-submit-btn {
			height: 70rpx;
			font-size: 26rpx;
		}
	}
</style>